package stateorder

import (
	"fmt"
	"time"
)

// OrderManager 订单管理器
type OrderManager struct {
	Orders map[string]*Order
}

func NewOrderManager() *OrderManager {
	return &OrderManager{
		Orders: make(map[string]*Order),
	}
}

// CreateOrder 创建订单
func (om *OrderManager) CreateOrder(items []string, totalAmount float64) *Order {
	id := fmt.Sprintf("order_%d", time.Now().UnixNano())
	order := NewOrder(id, items, totalAmount)
	om.Orders[order.ID] = order
	return order
}

// GetOrder 获取订单
func (om *OrderManager) GetOrder(orderID string) (*Order, bool) {
	order, ok := om.Orders[orderID]
	return order, ok
}

// ProcessOrder 处理订单
func (om *OrderManager) ProcessOrder(id string) {
	order, exists := om.Orders[id]
	if !exists {
		fmt.Printf("订单 %s 不存在\n", id)
		return
	}
	
	fmt.Printf("\n===== 处理订单 %s =====\n", id)
	fmt.Printf("当前状态: %s\n", order.State.GetName())
	
	// 根据状态决定下一步操作
	switch order.State.(type) {
	case *PendingState:
		if err := order.Pay(); err != nil {
			fmt.Println("操作失败:", err)
		}
	case *PaidState:
		if err := order.Ship(); err != nil {
			fmt.Println("操作失败:", err)
		}
	case *ShippedState:
		if err := order.Deliver(); err != nil {
			fmt.Println("操作失败:", err)
		}
	default:
		fmt.Println("订单已完成或取消，无需处理")
	}
}